using System.Text;
using System.Text.RegularExpressions;
using Identity.Application.Contracts.Commands;
using Identity.Application.Contracts.Requests.Account;
using Identity.Application.Contracts.Responses.Account;
using Identity.Application.UserAggregates.Commands;
using Identity.Application.Users.Commands;
using Identity.HttpAPI.Permission;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;


namespace Identity.HttpAPI.Controllers
{
    [ApiController]
    [Route("api/account")]
    public class AccountController : ControllerBase
    {

        private readonly IMediator _mediator;
        public AccountController(IMediator mediator)
        {
            _mediator = mediator;
        }

        
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody] RegiterUserRequest req)
        {
            CheckEmail(req.Email);

            var command = new RegisterUserCommand(req.Username, req.Email, req.Password);

            var result = await _mediator.Send(command);

            return Ok(result);
        }


        [HttpGet("{userId}/confirm-email-token")]
        [AllowAnonymous]
        public async Task<IActionResult> GetConfirmEmailToken(Guid userId)
        {
            var command = new GetConfirmEmailTokenCommand(userId);
            var result = await _mediator.Send(command);
            if (result == null) return NotFound("确认失败，请重新确认！");

            var confirmemaildto = new ConfirmEmailDto(result.userId, WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(result.token)));
            return Ok(confirmemaildto);
        }


        [HttpGet("{userId}/confirm-email")]
        [AllowAnonymous]
        public async Task<IActionResult> ConfirmEmail(Guid userId, [FromQuery] string token)
        {
            var command = new ConfirmEmailCommand(userId, token);
            var result = await _mediator.Send(command);
            if (!result.IsSuccess) return NotFound("确认失败，请重新确认！");
            return Ok(new { message = "邮箱已确认，可以登录" });
        }


        [HttpGet("{userId}/send-confirm-email")]
        [AllowAnonymous]
        public async Task<IActionResult> SendConfirmEmail(Guid userId)
        {
            var command = new SendConfrimEmailCommand(userId);
            var result = await _mediator.Send(command);
            if (!result.IsSuccess) return NotFound("确认失败，请重新确认！");
            return Ok(new { message = "邮箱已确认，可以登录" });
        }

        
        [HttpPost("change-password")]
        [Authorize]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest req)
        {
            var command = new ChangePasswordCommand(req.Id, req.currentPassword, req.newPassword);
            var result = await _mediator.Send(command);
            return Ok(result);
        }


        [HttpPut("Change-username")]
        [Authorize]
        public async Task<IActionResult> UpdateUser([FromBody] ChangeUserNameRequest req)
        {
            var command = new ChangeUserNameCommand(req.userId, req.newName);

            var result = await _mediator.Send(command);
            return Ok(result);
        }


        [HttpPut("Change-email")]
        [Authorize]
        public async Task<IActionResult> UpdateUser([FromBody] ChangeEmailRequest req)
        {
            var command = new ChangeEmailCommand(req.userId, req.newEmail);
            var result = await _mediator.Send(command);
            return Ok(result);
        }


        [HttpPost("forgot-password")]
        [AllowAnonymous]
        public async Task<IActionResult> ForgotPassword([FromQuery] string email)
        {
            CheckEmail(email);
            var command = new SendCodeEmailWithResetPasswordCommand(email);
            var result = await _mediator.Send(command);
            return Ok(result);
        }


        [HttpPost("reset-password")]
        [AllowAnonymous]
        public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest req)
        {
            var command = new ResetPasswordCommand(req.email, req.code, req.newPassword);
            await _mediator.Send(command);

            return Ok("密码重置成功");
        }

        [HttpGet("all-user-accounts")]
        [Authorize(Roles = "Admin")]
        [Permission("useraccount:item:view", "查看用户账号")]
        public async Task<IActionResult> GetAllUserAccountsAsync()
        {
            var command = new GetAllUserAccountCommand();
            var result = await _mediator.Send(command);
            return Ok(result);
        }


        private void CheckEmail(string email)
        {

            if (string.IsNullOrWhiteSpace(email))
                throw new ArgumentException("Email address cannot be empty.", nameof(email));

            if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase))
                throw new ArgumentException("Invalid email address format.", nameof(email));


        }


    }
}